package com.ddl.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.ddl.util.CheckSumBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 网易IM的HttpClient请求调用类
 * 
 * @author 说明：其他功能以及非必须参数的拓展使用，请自行参考网易IM文档。
 */
public class IMDao {
	/**
	 * 网易IM的HttpClient请求，要求所有请求均为post
	 * 
	 * @param url
	 *            请求路径
	 * @param map
	 *            请求参数
	 * @param appKey
	 * @param appSecret
	 * @return 返回结果使用json对象封装
	 * @throws Exception
	 */
	public JSONObject IMHttpClientPost(String url, Map<String, String> map,
			String appKey, String appSecret) throws Exception {
		// 1、 创建httpClient对象
		HttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);

		// 2、 需要放在Http Request Header中的校验参数
		String nonce = UUID.randomUUID().toString();
		String curTime = String.valueOf(System.currentTimeMillis() / 1000);
		String checksum = CheckSumBuilder
				.getCheckSum(appSecret, nonce, curTime);

		// 3、设置请求头
		httpPost.addHeader("AppKey", appKey);// 开发者平台分配的appkey
		httpPost.addHeader("Nonce", nonce);// 随机数（最大长度128个字符）
		httpPost.addHeader("CurTime", curTime);// 时间戳
		httpPost.addHeader("CheckSum", checksum);
		httpPost.addHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=utf-8");

		// 4、 设置请求的参数
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for (String key : map.keySet()) {
			if (map.get(key) == null || "".equals(map.get(key))) {
				continue;
			}
			nameValuePairs.add(new BasicNameValuePair(key, map.get(key)));
		}

		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

		// 5、 发送请求
		HttpResponse httpResponse = client.execute(httpPost);

		// 6、 处理结果数据
		String string = EntityUtils.toString(httpResponse.getEntity(), "utf-8");

		// 7.转换成json对象返回
		JSONObject fromObject = JSONObject.parseObject(string);
		return fromObject;
	}
}
